<template>
  <div class="app-container">
    <div class="filter-container">
      <div class="search-container">
        <el-input
          v-model="listQuery.uid"
          placeholder="飞友UID"
          style="max-width: 200px;"
          class="filter-item"
          @keyup.enter.native="handleFilter"
        />
        <el-input
          v-model="listQuery.name"
          placeholder="人员名称"
          style="max-width: 200px;"
          class="filter-item"
          @keyup.enter.native="handleFilter"
        />
        <el-input
          v-model="listQuery.tel"
          placeholder="联系方式"
          style="max-width: 200px;"
          class="filter-item"
          @keyup.enter.native="handleFilter"
        />
        <el-button
          class="filter-item"
          type="primary"
          @click="handleFilter"
        >
          {{ $t("table.search") }}
        </el-button>
      </div>
      <el-button v-if="Number(type) === 1" class="filter-item" type="primary" @click="feiyouInit">
        同步飞友
      </el-button>
      <el-button v-if="Number(type) === 1" style="margin: 0" type="primary" @click="handleCreate">
        新增
      </el-button>
    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%"
    >
      <el-table-column align="center" label="序号" width="80">
        <template slot-scope="scope">
          <span>{{ scope.$index + 1 + 1 * (listQuery.current - 1) * listQuery.size }}</span>
        </template>
      </el-table-column>

      <el-table-column width="200px" align="center" label="同步时间">
        <template slot-scope="scope">
          <span>{{
            new Date(scope.row.syncTime) | parseTime()
          }}</span>
        </template>
      </el-table-column>

      <el-table-column width="120px" align="center" label="员工姓名">
        <template slot-scope="scope">
          <span>{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column width="120px" align="center" label="联系方式">
        <template slot-scope="scope">
          <span>{{ scope.row.tel }}</span>
        </template>
      </el-table-column>
      <el-table-column width="120px" align="center" label="飞友UID">
        <template slot-scope="scope">
          <span>{{ scope.row.uid }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="人脸信息">
        <template slot-scope="scope">
          <div class="face-container">
            <!-- <el-upload
              v-if="!scope.row.faceList.length && Number(type) === 1"
              action=""
              :before-upload="beforeAvatarUpload"
              accept="image/jpeg,image/jpg,image/png"
              :limit="1"
              :show-file-list="false"
              :on-exceed="handleExceed"
              :http-request="(event) => addFace(event, scope.row.id)"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload> -->
            <div v-for="item in scope.row.faceList" :key="item.id">
              <!-- <el-upload
                action=""
                :before-upload="beforeAvatarUpload"
                accept="image/jpeg,image/jpg,image/png"
                :limit="1"
                :show-file-list="false"
                :on-exceed="handleExceed"
                :http-request="(event) => updateFace(event, item.id)"
              > -->
              <img
                :src="item.imagePath"
                :alt="item.name"
                style="
                  width: 40px;
                  height: 40px;
                  margin-left: 10px;
                  border-radius: 5px;
                "
              >
              <!-- </el-upload> -->
            </div>
          </div>
        </template>
      </el-table-column>

      <!-- <el-table-column width="100px" label="Importance">
        <template slot-scope="scope">
          <svg-icon v-for="n in +scope.row.importance" :key="n" icon-class="star" class="meta-item__icon" />
        </template>
      </el-table-column>

      <el-table-column class-name="status-col" label="Status" width="110">
        <template slot-scope="{row}">
          <el-tag :type="row.status | statusFilter">
            {{ row.status }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column min-width="300px" label="Title">
        <template slot-scope="{row}">
          <router-link :to="'/example/edit/'+row.id" class="link-type">
            <span>{{ row.title }}</span>
          </router-link>
        </template>
      </el-table-column> -->

      <el-table-column align="center" label="操作" :width="Number(type) === 1 ? 240 : 120">
        <template slot-scope="scope">
          <el-button
            v-if="Number(type) === 1"
            type="primary"
            size="small"
            @click="handleUpdate(scope.row)"
          >
            编辑
          </el-button>
          <el-popconfirm v-if="Number(type) === 1" title="确认删除吗？" @onConfirm="onDelete(scope.row.id)">
            <el-button
              slot="reference"
              type="danger"
              size="small"
              style="margin: 0 10px;"
            >
              删除
            </el-button>
          </el-popconfirm>
          <router-link :to="'/member/edit/' + scope.row.id">
            <el-button type="primary" size="small">
              查看
            </el-button>
          </router-link>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.current"
      :limit.sync="listQuery.size"
      @pagination="getList"
    />

    <el-dialog :title="textMap[dialogStatus]" width="320px" :visible.sync="dialogVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="90px"
      >
        <el-form-item label="姓名" prop="name">
          <el-input v-model="temp.name" />
        </el-form-item>
        <el-form-item label="电话号码" prop="tel">
          <el-input v-model="temp.tel" maxlength="11" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">
          {{ $t("table.cancel") }}
        </el-button>
        <el-button
          type="primary"
          @click="dialogStatus === 'create' ? createData() : updateData()"
        >
          {{ $t("table.confirm") }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { fetchList, addFace, updateFace, feiyouInit, addUser, updateUser, deleteUser } from '@/api/member'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination

export default {
  name: 'ArticleList',
  components: { Pagination },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        current: 1,
        size: 10,
        uid: '',
        name: '',
        tel: ''
      },
      timer: null,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '新增'
      },
      dialogVisible: false,
      temp: {
        userId: undefined,
        name: '',
        tel: ''
      },
      rules: {
        name: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
        tel: [{ required: true, message: '电话不能为空', trigger: 'blur' }]
      }
    }
  },
  computed: {
    ...mapGetters([
      'type'
    ])
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then((response) => {
        const { records, total } = response.object
        this.list = records || []
        this.total = total
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.current = 1
      this.getList()
    },
    resetTemp() {
      this.temp = {
        userId: undefined,
        name: '',
        tel: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs.dataForm.validate((valid) => {
        if (valid) {
          addUser(this.temp).then(() => {
            this.handleFilter()
            this.dialogVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = {
        userId: row.id,
        name: row.name,
        tel: row.tel
      }
      this.dialogStatus = 'update'
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          updateUser(this.temp).then(() => {
            this.list = this.list.map(res => {
              if (res.id === this.temp.userId) {
                return {
                  ...res,
                  name: this.temp.name,
                  tel: this.temp.tel
                }
              }
              return res
            })
            this.dialogVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    onDelete(id) {
      const formData = new FormData()
      formData.append('userId', id)
      deleteUser(formData).then(() => {
        this.list = this.list.filter(res => res.id !== id)
        this.total--
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success',
          duration: 2000
        })
      })
    },
    addFace({ file }, userId) {
      const formData = new FormData()
      formData.append('files', file)
      formData.append('userId', userId)
      addFace(formData).then(() => {
        this.$notify({
          title: '成功',
          message: '上传成功',
          type: 'success',
          duration: 2000
        })
        this.getList()
      })
    },
    updateFace({ file }, faceId) {
      const formData = new FormData()
      formData.append('files', file)
      formData.append('faceId', faceId)
      updateFace(formData).then(() => {
        this.$notify({
          title: '成功',
          message: '修改成功',
          type: 'success',
          duration: 2000
        })
        this.getList()
      })
    },
    handleExceed(files) {
      this.$message.error(
        `当前限制选择 6 个文件，本次选择了 ${files.length} 个文件`
      )
    },
    beforeAvatarUpload(file) {
      const isJPG = ['image/jpeg', 'image/jpg', 'image/png'].includes(
        file.type
      )

      if (!isJPG) {
        this.$message.error('人脸图片只能是jpg、jpeg、png格式!')
        return false
      }
      if (file.size < 10 * 1024) {
        this.$message.error('人脸图片大小不能小于10KB!')
        return false
      }

      if (file.size > 512 * 1024) {
        this.$message.error('人脸图片大小不能大于512KB!')
        return false
      }
      return true
    },
    feiyouInit() {
      if (this.timer) {
        return this.$message.warning('10s内不可重复点击!')
      }
      this.timer = setTimeout(() => {
        clearTimeout(this.timer)
      }, 10000)

      feiyouInit().then(() => {
        this.$notify({
          title: '成功',
          message: '同步成功',
          type: 'success',
          duration: 2000
        })
      })
    }
  }
}
</script>

<style scoped>
.edit-input {
  padding-right: 100px;
}
.cancel-btn {
  position: absolute;
  right: 15px;
  top: 10px;
}
.face-container {
  display: flex;
  align-items: center;
  flex-shrink: 0;
  overflow: hidden;
}
</style>
